package cool.xiaokang.familyaccount.controller;

import java.io.IOException;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.struts2.ServletActionContext;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.alibaba.fastjson.serializer.PropertyFilter;
import com.opensymphony.xwork2.ActionSupport;

import cool.xiaokang.familyaccount.pojo.Topic;
import cool.xiaokang.familyaccount.service.SearchService;
import cool.xiaokang.familyaccount.service.TopicService;
import cool.xiaokang.familyaccount.utils.PageBean;
import cool.xiaokang.familyaccount.utils.ResponseUtils;
import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
@Controller
@Scope("prototype")
public class SolrAction extends ActionSupport {
	private static final long serialVersionUID = -7716784739387686886L;

	private String topic_ids;
	private Integer page;
	private Integer rows;

	@Autowired
	private SearchService searchService;

	@Autowired
	private TopicService topicService;

	// 一键导入索引库
	@RequiresPermissions("solr-add")
	public String importIndex() throws IOException {
		String flag = "1";
		try {
			searchService.importIndex();
		} catch (Exception e) {
			flag = "0";
			e.printStackTrace();
		}
		ServletActionContext.getResponse().setContentType("text/json;charset=utf-8");
		ServletActionContext.getResponse().getWriter().write(flag);
		return NONE;
	}

	// 删除索引库
	@RequiresPermissions("solr-delete")
	public String delete() throws IOException {
		System.out.println("SolrAction-delete>>>" + topic_ids);
		String flag = "1";
		try {
			searchService.delete(topic_ids);
		} catch (Exception e) {
			flag = "0";
			e.printStackTrace();
		}
		ServletActionContext.getResponse().setContentType("text/json;charset=utf-8");
		ServletActionContext.getResponse().getWriter().write(flag);
		return NONE;
	}

	// 后台索引列表
	@RequiresPermissions("solr-list")
	public String pageQuery() throws IOException {
		PageBean pb = new PageBean();
		DetachedCriteria dc = DetachedCriteria.forClass(Topic.class);
		dc.add(Restrictions.eq("del", '0'));
		pb.setDetachedCriteria(dc); 
		pb.setCurrentPage(page);
		pb.setPageSize(rows);
		topicService.pageQuery(pb);
		PropertyFilter filter = new PropertyFilter() {
			@Override
			public boolean apply(Object object, String name, Object value) {
				boolean flag = true;
				if (name.equals("topic_content")) {
					flag = false;
				} else if (name.equals("user")) {
					flag = false;
				} else if (name.equals("region")) {
					flag = false;
				} else if (name.equals("replys")) {
					flag = false;
				}
				return flag;
			}
		};
		ResponseUtils.respPageBean(ServletActionContext.getResponse(), pb, filter);
		return NONE;
	}

	public String list() throws IOException {
		return "list";
	}
}
